package com.elvish.oda.busin.controller;

import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.elvish.oda.busin.pojo.Organization;
import com.elvish.oda.busin.service.OrganizationService;
import com.elvish.oda.common.pojo.EasyUITableData;
import com.elvish.oda.common.pojo.Page;
import com.elvish.oda.common.pojo.Result;
import com.elvish.oda.common.utils.ResultUtil;

@RestController
public class OrganizationController {

	@Autowired
	private OrganizationService organizationService;

	/**
	 * 初始化地域tree表格
	 * 
	 * @return easyui tree表格数据
	 */
	@PostMapping(value = "/organization/initOrganizationTable")
	public EasyUITableData initAreaTreeTable(Integer areaId, Page page) {
		EasyUITableData data = new EasyUITableData();
		QueryResult result = organizationService.findAll(page, areaId);
		if (result != null) {
			Pager pager = result.getPager();
			data.setRows(result.getList());
			data.setTotal(pager.getRecordCount());
		}
		return data;
	}

	/**
	 * 操作地域
	 * 
	 * @return easyui tree表格数据
	 */
	@PostMapping(value = "/organization/operOrganization/{oper}")
	public Result<Organization> operArea(Organization organization, @PathVariable("oper") Integer operFlag,
			@RequestParam(value = "ids[]") String[] ids) {
		Result result = new Result<>();
		try {

			if (operFlag == 1) {
				// 新增
				if (Lang.isEmpty(organization.getId())) {
					organizationService.save(organization);
				}
				// 更新
				else {
					organizationService.update(organization);
				}
			}
			// 删除
			else if (operFlag == 2) {
				organizationService.deleteByIds(ids);
			}
			result = ResultUtil.success();
		} catch (Exception e) {
			result = ResultUtil.fail(-1, "系统异常");
		}
		return result;
	}

}
